import React from "react";
import { Spin, Icon, message } from "antd";
import Condition from "components/condition";
import dashboardService from "containers/dashboard/dashboard.service";
import { eventTrack, messages } from "share/common";
import { connect } from "react-redux";
import constants from "share/constants";
import menuRoute from "routes/menuRoute";
import "styles/dashboard/dynamic-documents.scss";

import NullCard from "containers/dashboard/dashboard-component/null-card";
import ExampleTag from "containers/home/home-dashboard-share/example-tag";

import ApprovingEditImg from "images/dashboard/home-approve-doing.png";
import ApprovingPassImg from "images/dashboard/home-approve-pass.png";
import ApprovingRejectImg from "images/dashboard/home-approve-reject.png";
import EditingDrawbackImg from "images/dashboard/home-drawback.png";

const { If, Else } = Condition;

class DynamicDocuments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false,
      documentActive: [],
    };
  }

  componentWillMount() {
    this.getDocumentActive();
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  setLoading = () => {
    this.setState({ loading: true });
  };

  getRealData = () => {
    this.getDocumentActive();
  };

  getDocumentActive = () => {
    const { profile, trialTenant } = this.props;
    this.setState({ load: true });
    dashboardService.getLatestActive({}, trialTenant).then((res) => {
      const resultData = [];
      res.data.length &&
        res.data.map((item) => {
          if (!profile["ca.web.disabled"] || item.entityType !== "1001") {
            resultData.push(item);
          }
        });
      this.setState({
        load: false,
        documentActive: resultData,
      });
    });
  };

  goDocumentDetail = (item) => {
    const { trialTenant } = this.props;
    if (trialTenant) {
      // message.warn(messages('basic-1.key206')/*示例单据不可点击*/);
      return;
    }
    let url;
    const formType = Number(item.formType);
    if (formType < 3000) {
      if (formType === 2005 || formType === 2006) {
        url = menuRoute
          .getRouteItem("loan-detail")
          .url.replace(":formOID", item.formOID)
          .replace(":loanBillOID", item.entityOID)
          .replace(":pageFrom", "history");
      }
      //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）
      //status === 1001 编辑申请单
      if ((formType === 2001 || formType === 2002 || formType === 2003) && item.status === 1001) {
        url = menuRoute
          .getRouteItem("request-edit")
          .url.replace(":formOID", item.formOID)
          .replace(":applicationOID", item.entityOID);
      }
      if (formType === 2004 && item.status === 1001) {
        url = menuRoute
          .getRouteItem("jd-request-edit")
          .url.replace(":formOID", item.formOID)
          .replace(":applicationOID", item.entityOID);
      }
      if ((formType === 2001 || formType === 2002 || formType === 2003 || formType === 2004) && item.status !== 1001) {
        url = menuRoute
          .getRouteItem("request-detail")
          .url.replace(":formOID", item.formOID)
          .replace(":applicationOID", item.entityOID)
          .replace(":pageFrom", "my");
      }
    } else {
      url = menuRoute
        .getRouteItem("expense-report-detail")
        .url.replace(":expenseReportOID", item.entityOID)
        .replace(":pageFrom", "my");
    }
    this.context.router.push(url);
    eventTrack({
      category: "1218-新首页-埋点",
      action: "点击【单据动态】进入了单据",
      label: this.props.tenant.tenantName,
    });
    // window.open(`${window.ISIE9 ? "#" : ""}${url}`, "_blank");
  };

  goToLink = () => {
    this.context.router.push(menuRoute.getRouteItem("expense-report", "key").url);
  };

  render() {
    const { trialTenant, onConfirm, uniKey, menuTree, enableDrag } = this.props;
    const { load, documentActive } = this.state;
    return (
      <div id={`home-${uniKey}`} data-id={`home-${uniKey}`} className="dynamic-document-card two-third-width">
        <Spin spinning={load}>
          <div className="home-title">{messages("basic-1.key111") /*单据动态*/}</div>
          <div className="card-content">
            <Condition>
              <If value={documentActive.length || load}>
                <div className="active-content">
                  {documentActive.map((item) => (
                    <div
                      className={trialTenant ? "latest-item" : "latest-item hover"}
                      onClick={() => this.goDocumentDetail(item)}
                      key={item.entityOID}
                    >
                      <div className="dashboard-flex">
                        <div className="state-icon">
                          {item.rejectType === 1000 &&
                            constants.getTextByValue(Number(item.status), "documentStatus", "state") ===
                              "processing" && <img src={ApprovingEditImg} />}
                          {item.rejectType === 1000 &&
                            constants.getTextByValue(Number(item.status), "documentStatus", "state") === "success" && (
                              <img src={ApprovingPassImg} />
                            )}
                          {item.rejectType !== 1000 &&
                            constants.getTextByValue(
                              Number(`${item.status}${item.rejectType}`),
                              "documentStatus",
                              "state"
                            ) === "warning" && <img src={EditingDrawbackImg} />}
                          {item.rejectType !== 1000 &&
                            constants.getTextByValue(
                              Number(`${item.status}${item.rejectType}`),
                              "documentStatus",
                              "state"
                            ) === "error" && <img src={ApprovingRejectImg} />}
                        </div>
                        <div className="base-info">
                          {new Date(item.lastModifiedDate).format("yyyy-MM-dd hh:mm:ss")}
                          <span>
                            {item.approvalHistorys && item.approvalHistorys[0].operator
                              ? item.approvalHistorys[0].operator.fullName
                              : ""}
                          </span>
                          {item.approvalHistorys ? item.approvalHistorys[0].operationDescription : ""}
                          <div className="business-code f-right">{item.businessCode}</div>
                        </div>
                      </div>
                      <div className="form-info">
                        <span>{item.formName}</span>
                        <span className="f-right">
                          <span>{item.currencyCode}</span>
                          {this.filterMoney(item.totalAmount)}
                        </span>
                      </div>
                      {item.title || item.remark ? (
                        <div className="document-title">{`${item.title ? item.title : ""}${
                          item.title && item.remark ? "，" : ""
                        }${item.remark ? item.remark : ""}`}</div>
                      ) : (
                        <div className="document-title">-</div>
                      )}
                    </div>
                  ))}
                  {!load && (
                    <div className="dynamic-document-tips">{messages("basic-1.key112") /*最多显示5条（近60天）*/}</div>
                  )}
                </div>
              </If>
              <Else>
                <NullCard
                  top={40}
                  onClick={this.goToLink}
                  imgType={"dynamicDoc"}
                  btnMessage={menuTree.keyUrl["expense-report"] ? messages("basic-1.key207") /*前往报销*/ : ""}
                  message={messages("basic-1.key113") /*这里将显示近60天的单据动态*/}
                />
              </Else>
            </Condition>
          </div>
        </Spin>
        <ExampleTag show={trialTenant} onConfirm={onConfirm} />
        {enableDrag && <div className="toggle-drag-box" />}
      </div>
    );
  }
}

DynamicDocuments.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(DynamicDocuments);
